package com.yunji.web.common;

import com.google.code.kaptcha.Producer;
import com.yunji.common.base.BaseController;
import com.yunji.common.base.RuoYiConfig;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.CacheCode;
import com.yunji.common.constant.General;
import com.yunji.common.utils.sign.Base64;
import com.yunji.common.utils.uuid.UUIDUtils;
import com.yunji.system.service.ISysConfigService;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
public class MathCaptchaController extends BaseController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Resource
    private ISysConfigService configService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Response<Map<String,Object>> getCode() {
        Map<String,Object> map = new HashMap();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        map.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ResponseHelper.success(map);
        }

        // 保存验证码信息
        String uuid = UUIDUtils.simpleUUID();
        String verifyKey = CacheCode.CAPTCHA_CODE_KEY + uuid;

        String capStr;
        String code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.set(verifyKey, code, General.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return ResponseHelper.failure(e.getMessage());
        }

        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return ResponseHelper.success(map);
    }
}
